<?php

namespace App\Listeners\CallingCards;

use App\Events\OpenShop\OrderSignedEvent;
use App\Listeners\BaseListener;
use App\Models\FeishuCallingCard\FeishuCallingCardFranchiseeClue;
use App\Models\FeishuCallingCard\FeishuCallingCardFranchiseeSignRecord;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;

class CallingCardsOrderSignedListener extends BaseListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param OrderSignedEvent $event
     * @return void
     */
    public function handle(OrderSignedEvent $event)
    {
        $orderMobile = (string)OpenShopUserBaseInfoModel::query()
            ->where('orderNo', $event->order->orderNo)
            ->value('mobile');
        if (!strlen($orderMobile)) {
            return;
        }
        // 加盟商的rms中uid
        $invitorId = '';
        FeishuCallingCardFranchiseeClue::query()
            ->where('mobile', $orderMobile)
            ->orderBy('createdAt', 'desc')
            ->chunk(100, function ($clues) use (&$invitorId) {
                foreach ($clues as $clue) {
                    if ('' === $invitorId && 'u' === mb_substr($clue->invitorId, 0, 1)) {
                        $invitorId = explode('s', mb_substr($clue->invitorId, 1))[0];
                    }
                }
            });
        if ('' === $invitorId) {
            return;
        }
        $record                    = new FeishuCallingCardFranchiseeSignRecord();
        $record->uid               = $invitorId;
        $record->invitee_mobile    = $orderMobile;
        $record->invitee_shop_code = $event->order->shopCode;
        $record->save();

    }
}
